package com.example.parsexml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * project:
 * author: wzq
 * date: 2014/7/31
 * description: pull 方式也是事件驱动，且与模型关系紧密
 */
public class Pull {
    public static List<ModelStu> parse(InputStream is) {
        List<ModelStu> stuList = null;

        try {
            XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
            parser.setInput(is, "utf8");
            int eventType = parser.getEventType();
            ModelStu tmpStu = null;
            while(eventType != XmlPullParser.END_DOCUMENT) {
                switch(eventType) {
                    //
                    case XmlPullParser.START_DOCUMENT:
                        stuList = new ArrayList<ModelStu>();
                        break;

                    //
                    case XmlPullParser.START_TAG:
                        String startTag = parser.getName();
                        //Log.i("Pull", "tagName=" + startTag);
                        if("stu".equals(startTag)) {
                            tmpStu = new ModelStu();
                            String id = parser.getAttributeValue(parser.getNamespace(), "id");//TODO 获取属性
                            tmpStu.setId(id);
                        } else if("name".equals(startTag) && null != tmpStu) {
                            tmpStu.setName(parser.nextText());
                        } else if("age".equals(startTag) && null != tmpStu) {
                            int age = Integer.parseInt(parser.nextText());
                            tmpStu.setAge(age);
                        } else if("sex".equals(startTag) && null != tmpStu) {
                            tmpStu.setSex(parser.nextText());
                        }
                        break;

                    //
                    case XmlPullParser.END_TAG:
                        String endTag = parser.getName();
                        if("stu".equals(endTag)) {
                            stuList.add(tmpStu);
                            tmpStu = null;
                        }
                        break;
                }
                eventType = parser.next();//TODO
            }
        } catch(XmlPullParserException xppe) {
            xppe.printStackTrace();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
        return stuList;
    }
}
